﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using SoftwareConsulting.BI11.Studio.Core.Users;
using SoftwareConsulting.BI11.Studio.InternalServices;

namespace SoftwareConsulting.BI11.Studio.UI.Users
{
    public partial class LogOnDialog : Form
    {        
        private int _failedTriesCounter;
        private bool _toLightCaption;
        private IUsersList _users;

        /// <summary>
        /// Инициализация диалога
        /// </summary>
        private void Initialize()
        {
            versionLabel.Text += " " + Application.ProductVersion;
            string copyr = string.Empty;
            object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
            if (attributes.Length == 0)
            {
                copyr = string.Empty;
            }
            copyr = ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
            copyrightLabel.Text = copyr;
            _failedTriesCounter = 0;            
            RollUp(false);            
        }        

        /// <summary>
        /// Включает/выключает элементы управления
        /// </summary>
        private void SetButtonsState(bool state)
        {
            LoginBox.Visible = state;
            PasswordBox.Visible = state;
            loginLabel.Visible = state;
            pwdLabel.Visible = state;
            OKButton.Visible = state;
        }

        /// <summary>
        /// Сворачивает форму медленно или быстро
        /// </summary>
        private void RollUp(bool slowly)
        {            
            SetButtonsState(false);
            copyrightLabel.Visible = false;
            if (slowly)
            {
                while (limitLabel.Top > descLabel.Top + descLabel.Font.Height * 3)
                {
                    this.Height = this.Height - 5;
                }
            }
            this.Height = descLabel.Top + descLabel.Font.Height * 3 + this.Height - limitLabel.Top;
            copyrightLabel.Visible = true;
        }

        /// <summary>
        /// Разворачивает форму
        /// </summary>
        private void RollDown()
        {
            Update();
            copyrightLabel.Visible = false;
            while (this.Height < 360)
            {
                this.Height = this.Height + 5;
            }
            this.Height = 360;
            copyrightLabel.Visible = true;
            SetButtonsState(true);
            LoginBox.Focus();
        }

        /// <summary>
        /// Подключается под указанным пользователем и закрывает диалог
        /// </summary>
        private void ApplyAndClose()
        {            
            if (!_users.TryConnect(LoginBox.Text, PasswordBox.Text))
            {
#if DEBUG
#else     
                DialogResult = DialogResult.None;
                GeneralMethods.ShowUserError(Resources.BI_LOGIN_FAILED);                
                LoginBox.Focus();
                LoginBox.SelectAll();
                _failedTriesCounter++;
                if (_failedTriesCounter == 3)
                {                                        
                    RollUp(true);                    
                    limitLabel.Visible = true;                    
                }
                return;
#endif
            }
            RollUp(true);
            LoggedLabel.Visible = true;
            DialogResult = DialogResult.OK;
        }

        public LogOnDialog(IUsersList users)
        {
            _toLightCaption = true;            
            _users = users;
            InitializeComponent();
        }

        private void ChangeLabelsColors()
        {            
            int index = _toLightCaption ? 3 : -3;            
            Color newColor = Color.FromArgb(0, nameLabel.ForeColor.R + index, nameLabel.ForeColor.G + index, nameLabel.ForeColor.B + index);
            if (_toLightCaption && (newColor.G >= 220))
            {
                _toLightCaption = false;
            }
            else
            {
                if (!_toLightCaption && (newColor.G <= 195))
                {
                    _toLightCaption = true;
                }
            }
            nameLabel.ForeColor = newColor;
            index = -index;
            newColor = Color.FromArgb(0, descLabel.ForeColor.R + index, descLabel.ForeColor.G + index, descLabel.ForeColor.B + index);
            descLabel.ForeColor = newColor;
        }         

        private void OnEnterBox(TextBox textBox)
        {
            textBox.BackColor = Color.Aquamarine;            
            textBox.SelectAll();
        }

        private void OnUnenterBox(TextBox textBox)
        {
            textBox.BackColor = Color.PaleTurquoise;            
        }

        private void OnHoverBox(TextBox textBox)
        {
            if (!textBox.Focused)
            {
                textBox.BackColor = Color.LightCyan;
            }
        }

        private void OnLeaveBox(TextBox textBox)
        {
            if (!textBox.Focused)
            {
                textBox.BackColor = Color.PaleTurquoise;
            }
        }

        private void LoginDialog_Load(object sender, EventArgs e)
        {
            Initialize();
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            ApplyAndClose();
        }

        private void LoginBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                Close();
            }
        }        

        private void PasswordBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                Close();
            }
        }

        private void OKButton_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                Close();
            }
        }

        private void LoginBox_Enter(object sender, EventArgs e)
        {
            OnEnterBox(LoginBox);            
        }

        private void PasswordBox_Enter(object sender, EventArgs e)
        {
            OnEnterBox(PasswordBox);
        }

        private void LoginBox_MouseHover(object sender, EventArgs e)
        {
            OnHoverBox(LoginBox);
        }

        private void PasswordBox_MouseHover(object sender, EventArgs e)
        {
            OnHoverBox(PasswordBox);
        }

        private void PasswordBox_MouseLeave(object sender, EventArgs e)
        {
            OnLeaveBox(PasswordBox);
        }

        private void LoginBox_MouseLeave(object sender, EventArgs e)
        {
            OnLeaveBox(LoginBox);
        }

        private void LoginBox_Leave(object sender, EventArgs e)
        {
            OnUnenterBox(LoginBox);
        }

        private void PasswordBox_Leave(object sender, EventArgs e)
        {
            OnUnenterBox(PasswordBox);
        }

        private void ColorChanger_Tick(object sender, EventArgs e)
        {
            ChangeLabelsColors();            
        }

        private void LogOnDialog_Shown(object sender, EventArgs e)
        {
            RollDown();
        }

        private void LogOnDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_failedTriesCounter == 3)
            {
                DialogResult = DialogResult.Abort;
            }
        }
    }
}
